package com.rfchina.okr.xianren.manager;

import java.math.BigDecimal;
import java.util.Date;

import com.rfchina.okr.xianren.model.MoneyFlow;
import com.rfchina.okr.xianren.model.RechargeInfo;
import com.rfchina.okr.xianren.model.UserMoney;
import com.rfchina.okr.xianren.model.WithdrawInfo;
import com.rfchina.okr.xianren.util.MoneyObjectType;

public class MyMoneyManager {
	private MyMoneyManager() {
	}

	private static final MyMoneyManager single = new MyMoneyManager();

	public static MyMoneyManager getInstance() {
		return single;
	}

	public int changeMoney(Date lockTime, Long uid, Integer id, String appid, BigDecimal money, String billAuditComment,
			MoneyObjectType type) {
		UserMoney um = UserMoney.dao.findById(uid);
		BigDecimal beforeMoney = um.getMoney();
		if (um.getLocking() == 1) {
			// continue;
			return 0;
		}
		if (type.equals(MoneyObjectType.withdraw) && beforeMoney.compareTo(money) < 0) {
			WithdrawInfo t = new WithdrawInfo();
			t.setId(id);
			// 状态 1提现中,2成功成功,3提现失败
			t.setStatus(3);
			t.setRemarks("可以提现的金额不足!");
			t.setEndTime(new Date());
			t.update();
			return 0;
		}

		UserMoney umupdate = new UserMoney();
		umupdate.setUid(uid);
		umupdate.setLocking(1);
		if (!umupdate.update()) {
			// continue;
			return 0;
		}

		umupdate.setLockTime(lockTime);
		umupdate.update();

		MoneyFlow mf = new MoneyFlow();
		mf.setAppid(appid);
		mf.setMoney(money);
		mf.setBeforeMoney(beforeMoney);
		mf.setCreateTime(lockTime);
		BigDecimal balance = beforeMoney.add(money);
		mf.setBalance(balance);
		mf.setRemark(billAuditComment);
		mf.setObjectId(id);
		mf.setObjectType(type.name());
		mf.setUid(uid);
		mf.save();
		Integer flow = mf.getId();
		//
		if (type.equals(MoneyObjectType.recharge)) {
			RechargeInfo t = new RechargeInfo();
			t.setId(id);
			// 状态 1支付中,2支付成功,3支付超时
			t.setStatus(2);
			t.setBillAuditComment(billAuditComment);
			t.setBillTime(lockTime);
			t.setMoneyFlowId(flow);
			t.update();
		} else if (type.equals(MoneyObjectType.withdraw)) {
			WithdrawInfo t = new WithdrawInfo();
			t.setId(id);
			// 状态 1提现中,2成功成功,3提现失败
			t.setStatus(2);
			t.setEndTime(new Date());
			t.setMoneyFlowId(flow);
			t.update();
		} else {

		}
		//
		um = new UserMoney();
		um.setUid(uid);
		um.setMoney(balance);
		um.setLocking(0);
		um.setLastFlowId(flow);
		um.update();
		return flow;
	}

	// public static void main(String[] args) {
	// System.out.println(MoneyObjectType.recharge.name());
	// System.out.println(MoneyObjectType.recharge.getTitle());
	// }
}
